<?php

namespace component\system\system_user_auth;

use common\ApiError;
use common\logic\Logic;


class SystemUserAuth extends Logic
{


    /**
     * @var array
     */
    public $fields = [
        'id',
        'user_id',
        'role_id',
        'auth_id',
        'menu',
        'create_time',
    ];

    /**
     * @return SystemUserAuthModel|\think\Model
     */
    protected function model()
    {
        return new SystemUserAuthModel();
    }

    /**
     * @param $user_id
     * @param $params
     * @return bool|mixed|string
     */
    public function setUserAuth($user_id, $params)
    {
        if (empty($user_id) || empty($params) || !is_array($params)) {
            ApiError::instance()->message('参数错误');
            return false;
        }

        $record = $this->getByUserId($user_id);

        if ($record) {
            $params['id'] = $record['id'];
        } else {
            $params['user_id'] = $user_id;
        }

        return $this->save($params);
    }


    /**
     * @param $user_id
     * @return array|bool|null|SystemUserAuthModel
     */
    public function getByUserId($user_id)
    {
        if (empty($user_id)) {
            return false;
        }
        return $this->find(['user_id' => $user_id]);
    }

    /**
     * @param $user_id
     * @return mixed|null
     */
    public function getRoleIdListByUserId($user_id)
    {
        $record = $this->getByUserId($user_id);

        return $record['role_id'] ?? null;
    }

    /**
     * @param $user_id
     * @return mixed|null
     */
    public function getAuthIdListByUserId($user_id)
    {
        $record = $this->getByUserId($user_id);

        return $record['auth_id'] ?? null;
    }

    /**
     * @param $user_id
     * @return mixed|null
     */
    public function getMenuListByUserId($user_id)
    {
        $record = $this->getByUserId($user_id);

        return $record['menu'] ?? null;
    }
}